package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.model.common.dtos.ApUser;
import com.zhentao.model.common.dtos.LoginDto;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.service.ApUserService;
import com.zhentao.mapper.ApUserMapper;
import com.zhentao.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
* @author Administrator
* @description 针对表【ap_user(APP用户信息表)】的数据库操作Service实现
* @createDate 2024-05-30 14:12:10
*/
@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser>
    implements ApUserService{

    @Resource
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.正常登录（手机号+密码登录）
        Map<String,Object> map =new HashMap<>();
        //判断账号和密码是否为空
        if(!StringUtils.isEmpty(loginDto.getPhone()) && !StringUtils.isEmpty(loginDto.getPassword())) {
            // return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"手机或密码为空");

            //验证用户是否存在：查询数据库
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone, loginDto.getPhone());
            ApUser apUser = this.apUserMapper.selectOne(wrapper);
            if (Objects.isNull(apUser)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "手机或密码错误");
            }
            //判断密码+盐是否正确
            String salt = apUser.getSalt();
            String pswd = loginDto.getPassword();

            pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
//       if(! pswd.equalsIgnoreCase(loginDto.getPassword())){
            if (!pswd.equalsIgnoreCase(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
            }
            //生成token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            map.put("token", token);
            //把盐和密码置空（安全）
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user", apUser);
            //返回token：令牌
            return ResponseResult.okResult(map);
        }else{
             //游客
             String token = AppJwtUtil.getToken(0L);
             map.put("token", token);
             return ResponseResult.okResult(map);
        }

    }
}




